package de.slothsoft.wasbinich.tools;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import de.slothsoft.wasbinich.core.FullPicture;
import de.slothsoft.wasbinich.core.WasBinIch;
import de.slothsoft.wasbinich.core.database.Database;
import de.slothsoft.wasbinich.swingclient.database.SwingWebserviceDatabase;
import de.slothsoft.wasbinich.swingclient.io.ImageUtil;
import de.slothsoft.wasbinich.tools.internal.CsvParser;

public class CsvFileImporter {

    static {
	WasBinIch.DEBUG = true;
    }

    private static final File FILE = new File("src/tools/resources/13-10-27.csv");
    private static final Database database = new SwingWebserviceDatabase();

    public static void main(String[] args) throws Exception {
	Database.initInstance(database);
	String source = new String(Files.readAllBytes(FILE.toPath()));
	convert(source);
	System.out.println("Finished.");
    }

    public static void convert(String source) throws Exception {
	CsvParser<FullPicture> parser = new CsvParser<>(FullPicture.class);
	parser.setSeparator(";");

	for (FullPicture picture : parser.parse(source)) {
	    System.out.println("Importing " + picture.section);
	    convertFileToString(picture);
	    database.getManagerBean().createPicture(picture);
	}
    }

    public static void convertFileToString(FullPicture picture) throws IOException {
	picture.section = doConvertFileToString(picture.section);
	picture.bigPicture = doConvertFileToString(picture.bigPicture);
    }

    private static String doConvertFileToString(String imagePath) throws IOException {
	if (imagePath == null || imagePath.isEmpty())
	    return null;
	File imageFile = new File(imagePath);
	if (imageFile.exists())
	    return ImageUtil.convertFileToString(imageFile);
	return null;
    }

}
